package com.xing.hosp.receiver;

import com.xing.hosp.service.ScheduleService;
import com.xing.hospital.model.hosp.Schedule;
import com.xing.hospital.model.vo.msm.MsmVo;
import com.xing.hospital.model.vo.order.OrderMqVo;
import com.xing.rabbitmq.constant.MqConst;
import com.xing.rabbitmq.service.RabbitService;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.messaging.Message;

/**
 * @author 邢福豪
 * @date 2022/8/11 15:58
 */

@Component
public class HospitalReceiver {

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private RabbitService rabbitService;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ORDER, durable = "true"),
            exchange = @Exchange(value = MqConst.EXCHANGE_DIRECT_ORDER),
            key = {MqConst.ROUTING_ORDER}
    ))
    public void receiver(Message message) {
        OrderMqVo orderMqVo = (OrderMqVo) message.getPayload();
        if (null != orderMqVo.getAvailableNumber()) {
            //下单成功更新预约数
            Schedule schedule = scheduleService.getScheduleId(orderMqVo.getScheduleId());
            schedule.setReservedNumber(orderMqVo.getReservedNumber());
            schedule.setAvailableNumber(orderMqVo.getAvailableNumber());
            scheduleService.update(schedule);
        } else {
            //取消预约更新预约数
            Schedule schedule = scheduleService.getScheduleId(orderMqVo.getScheduleId());
            int availableNumber = schedule.getAvailableNumber().intValue() + 1;
            schedule.setAvailableNumber(availableNumber);
            scheduleService.update(schedule);
        }
        //发送短信
        MsmVo msmVo = orderMqVo.getMsmVo();
        if (null != msmVo) {
            //订单服务器模块，监听器监听到消息后，进行消费，发送短信消息，发消息给rabbitMQ的MSM队列，短信服务器模块监听器监听到消息后，进行消费，调用发送短信方法，进行短信发送
            rabbitService.sendMessage(MqConst.EXCHANGE_DIRECT_MSM, MqConst.ROUTING_MSM_ITEM, msmVo);
        }

    }


}
